﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace ECSE6770.Controllers
{
    [RequireHttps]
    [Authorize(Roles = "Admin")]
    public class VideoController : BaseAdminController
    {
        public ActionResult Index()
        {
            return View(Db.Videos.ToList());
        }

        public ActionResult Details(int id)
        {
            return View(Db.Videos.First(v => v.Id == id)); 
        }

        public ActionResult New()
        {
            return View("Edit");
        }

        public ActionResult Edit(int id)
        {
            return View(Db.Videos.First(v => v.Id == id));
        }

        public ActionResult Delete(int id)
        {
            var video = Db.Videos.First(v => v.Id == id);
            VideoManager.DeleteVideoFile(video);
            video.Deleted = true;
            Db.SaveChanges();
            return Success("Video Deleted", String.Concat(video.Title, " has been successfully deleted."), "View All Videos", Url.Action("Index", "Video"));
        }

        [HttpPost]
        public ActionResult Edit(Video model, HttpPostedFileBase videofile)
        {
            if (ModelState.IsValid)
            {
                model.DatePosted = DateTime.Now;
                if (model.Id > 0)
                {
                    //updating
                    if (videofile != null)
                        VideoManager.UpdateVideoFile(model, videofile);

                    var entry = Db.Entry(model);
                    entry.State = System.Data.EntityState.Modified;
                    //update the related videos too
                    entry.Collection(v => v.RelatedProducts).Load();
                    model.UpdateRelatedItems(Db);

                    Db.SaveChanges();
                    return Success("Video Updated", "Your video has been successfully update.", "View All Videos", Url.Action("Index"));
                }
                else
                {
                    //new video
                    model.FileName = VideoManager.StoreVideo(videofile);
                    model.MimeType = videofile.ContentType;
                    model.UpdateRelatedItems(Db);
                    Db.Products.Add(model);
                    Db.SaveChanges();
                    return Success("Video Added", "Your video has been successfully added.", "View All Videos", Url.Action("Index"));
                }
            }
            else
                return View();
        }
    }
}
